<!--
 * @Descripttion: 上传附件和提供下载附件。\n 依赖下载插件指令 v-downLoad
 * @Author: chendingfengmail@163.com
 * @version: 
 * @Date: 2021-06-22 14:53:03
 * @LastEditors: luozhenfu
 * @LastEditTime: 2022-06-21 15:26:42
-->
<template>
  <div class="dd-file-upload-text" style="float: left">
    <div>
      <el-upload
        v-if="!isPreview"
        action="fakeaction"
        ref="ddFileUploadText"
        :on-change="handleOnChange"
        :accept="accept"
        list-type="text"
        :file-list="fileList"
        :show-file-list="showFileList"
        :limit="fileLimit"
        :on-exceed="limitCheck"
        :on-remove="handleRemoveFile"
        :http-request="actionUpload">
          <el-button slot="trigger" size="small" :type="buttonType">{{buttonName}}</el-button>
          <!-- 
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> 
          <div slot="tip" class="el-upload__tip">只能上传附件，且不超过50MB</div>
          -->
      </el-upload>
      <div v-else v-for="item in previewFileUrlList" :key="item.id" v-downLoad="{url: item.url, name: item.name}" class="files">
        <i class="el-icon-tickets"></i>
        <span>{{item.name}}</span>
        <i class="el-icon-download"></i>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "dd-file-upload-text",
  props: {
    // 是否上传或者预览下载文件 模式
    isPreview: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 是否显示文件列表
    showFileList: {
      type: Boolean,
      default: () => {
        return true;
      }
    },
    // 按钮名称
    buttonName: {
      type: String,
      default: () => {
        return "选取文件";
      }
    },
    // 按钮类型
    buttonType: {
      type: String,
      default: () => {
        return "primary";
      }
    },
    // 限制上传文件的类型（文件后缀带小数点，多个类型以逗号隔开）: return ".jpg,.jpeg,.png,.JPG,.JPEG";
    accept: {
      type: String,
      default: () => {
        return "";
      },
    },
    // 限制上传文件的个数
    fileLimit: {
      type: Number,
      default: () => {
        return 9;
      },
    },
    // 文件列表
    fileList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 预览下载文件列表
    previewFileUrlList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    /**
     * 执行上传的钩子
     * 返回一个 Promise 对象
     */
    uploadRequest: {
      type: Function,
      required: true,
      default: function (formData) {
        return null;
      },
    },
    /**
     * 删除文件的回调
     */
    onRemoveFile: {
      type: Function,
      default: function (file, fileList) {
        return null;
      },
    },
    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     */
    onChange: {
      type: Function,
      default: function (file, fileList) {
        return null;
      },
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      imagePreviewVisible: false,
      removeBtnDisable: false,
      cacheFileNum: 0,
      slightlyFile: {},
    };
  },
  created() {},

  watch: {
    cacheFileNum(val, oldVal) {
    },
    fileList(val, oldVal) {
      this.cacheFileNum = val.length;
    },
  },
  methods: {
    handleOnChange(file, fileList) {
      this.onChange(file, fileList);
      this.slightlyFile = file;
    },

    // 检查文件个数
    limitCheck() {
      this.$message({
        type: "warning",
        message: `最多可以上传 ${this.fileLimit} 个附件`,
      });
    },

    // 检查文件类型
    fileTypeCheck(file) {
      // 获取可接受的文件格式
      let fileTypes = this.accept.split(",");
      // 无格式不校验文件类型
      if(!fileTypes || '' === fileTypes[0]) {
        return false
      }
      let fileType = file.name.substring(file.name.lastIndexOf("."));
      if (fileTypes.indexOf(fileType) != -1) {
        return false;
      }
      return true;
    },

    // 文件选择回调
    checkFile(file) {
      if (this.fileTypeCheck(file)) {
        this.$message.error(`只能上传 [${this.accept}] 格式的附件!`);
        this.$refs.ddFileUploadText.handleRemove(file); //删除缩略图
        return false;
      }
      const fileSize = file.size / 1024 / 1024 < 50;
      if (!fileSize) {
        this.$message.error("上传文件大小不能超过 50MB!");
        this.$refs.ddFileUploadText.handleRemove(file); //删除缩略图
        return false;
      }

      return true;
    },

    // 执行上传
    actionUpload(params) {
      let _this = this;
      if (!_this.checkFile(this.slightlyFile)) {
        return false;
      }
      console.log(this.slightlyFile);
      let loadFile = this.slightlyFile;
      let upFormData = new FormData();
      upFormData.append("file", loadFile.raw);
      _this
        .uploadRequest(upFormData)
        .then((res) => {
          _this.fileList.push({
            id: res.value.id,
            url: res.value.url,
            name: res.value.name,
          });
          _this.cacheFileNum++;
        })
        .catch((error) => {
          this.$refs.ddFileUploadText.handleRemove(params.file); //删除缩略图
          this.deleteFileList(params.file);
        });
    },

    // 删除已上传文件
    handleRemoveFile(file, fileList) {
      this.onRemoveFile(file, fileList);
      this.deleteFileList(file);
    },
    deleteFileList(file) {
      this.cacheFileNum--;
      for (var i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
        }
      }
    },
  },
};
</script>
<style lang="scss">
.dd-file-upload-text {
  .files{
    color: #2f74ff;
  }
  .files>span{
    margin: 0 10px;
  }
  .el-upload__tip{
    color: red;
    text-align: left !important;
  }
}
</style>